#pragma once

#include <iostream>
#include <memory>
#include "reactor.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"
#include "Log.hpp"
#include "connection.hpp"
#include <functional>

using func_t = std::function<std::string(std::string&)>;

class IOService : public connection
{

    const int size = 1024;

public:
    IOService(int sockfd)
    {
        setNonBlock(_sockfd);
        setSockfd(sockfd);
        setEvents(EPOLLIN | EPOLLET);
    }
    ~IOService()
    {
    }
    virtual void sender() override
    {
    }
    virtual void recever()
    {

        while (true)
        {

            // LOG(LogLevel::DEBUG) << "haha, I am recver";
            // 1. 读取所有的数据
            std::string buffer;
            ssize_t n = ::recv(_sockfd, (void *)buffer.c_str(), size, 0);
            if (n > 0)
            {
                // 读取成功
                append(buffer);
            }
            if (n == 0)
            {
                // 对端关闭链接
                excepter();
                return;
            }
            else
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                {
                    break;
                }
                else if (errno == EINTR)
                {
                    continue;
                }
                else
                {
                    // 发生错误
                    excepter();
                    return ;
                }
            }
        }
        // 走到下面说明现在的数据全都读完了
        std::cout << "outString: \n" << inString() << std::endl;
        // 你能确定你读到的信息就是一个完整的报文呢吗？， 协议！
        std::string result;
        if (_onMessage)
            _onMessage(inString());
    }
    virtual void excepter()
    {
        // IO读取的失败，将所有的异常事件转换为读写事件
    } 
    void registerOnMessage(func_t onMessage) { _onMessage = onMessage;}
    private:
    func_t _onMessage;
};